import 'package:star_author/config/ui_constant.dart';
import 'package:star_author/deer/routers/fluro_navigator.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/widgets/qr_code_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mobile_scanner/mobile_scanner.dart';

class QrCodeScannerPage extends StatefulWidget {
  const QrCodeScannerPage();

  @override
  _QrCodeScannerPageState createState() => _QrCodeScannerPageState();
}

class _QrCodeScannerPageState extends State<QrCodeScannerPage> {
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  late MobileScannerController controller;

  @override
  void dispose() {
    controller.stop();
    controller.dispose();
    super.dispose();
  }

  @override
  void reassemble() {
    super.reassemble();
    controller.stop();
  }

  @override
  void initState() {
    // TODO: implement initState
    controller = MobileScannerController(
      torchEnabled: false,
      facing: CameraFacing.back,
    );
    super.initState();
  }

  bool status = true;

  void stop() {
    this.controller.stop();
    status = false;
  }

  void start() {
    status = true;
    this.controller.start();
  }

  void _onQRViewCreated(Barcode barcode, MobileScannerArguments? args) {
    if (status) {
      LogUtil.v("object-$status");
      stop();
      if (barcode.rawValue?.isNotEmpty ?? false) {
        NavigatorUtils.goBackWithParams(context, barcode.rawValue ?? '');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final scanArea = (MediaQuery.of(context).size.width < 400 ||
            MediaQuery.of(context).size.height < 400)
        ? 250.0
        : 300.0;
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.black,
        title: Text(
          "二维码/条形码",
          style: TextStyle(fontSize: 18.sp, color: Colors.white),
        ),
      ),
      body: Stack(
        children: <Widget>[
          MobileScanner(
            allowDuplicates: true,
            key: qrKey,
            controller: controller,
            onDetect: _onQRViewCreated,
          ),
          Center(
              child: Container(
            decoration: ShapeDecoration(
              shape: QrScannerOverlayShape(
                borderColor: UIConstant.colorE02020,
                borderRadius: 5,
                borderLength: 20,
                borderWidth: 5,
                cutOutSize: scanArea,
              ),
            ),
          )),
        ],
      ),
    );
  }
}
